<?php

namespace App\Http\Controllers;

use App\Http\Service\ChapterService;
use App\Http\Service\QuestionsService;
use App\Models\Chapters;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChapterController extends  Controller{

    public function index(Request $request){
        $nestedList = Chapters::getNestedList('title','id','...');
        return view('chapter.index',[
            'nestList' => $nestedList
        ]);
    }

    public function createNode(Request $request){
        $int_pid = $request->pid?$request->pid:0;
        return view('chapter.create',[
            'pid' => $int_pid
        ]);
    }

    public function doCreateNode(Request $request){
        $int_pid = $request->pid ? $request->pid : 0;
        $arr_info = $request->info;
        if ($int_pid){
            $result = ChapterService::createNode($int_pid, $arr_info);
        }else{
            $result = ChapterService::createRootNode($arr_info);
        }
        return redirect('/chapter/index');
        return redirect()->back();
    }

    public function edit(Request $request){
        $int_pid = $request->id;
        $obj_chaperInfo = ChapterService::getNodeInfo($int_pid);
        return view('chapter.edit',[
            'info' => $obj_chaperInfo
        ]);
    }

    public function doEdit(Request $request){
        $arr_info = $request->info;
        if(ChapterService::updateNodeInfo($arr_info)){
            return redirect('/chapter/index');
        }
        return redirect()->back();
    }

    public function delete(Request $request){
        $int_id = $request->id;
        if(ChapterService::deleteNode($int_id)){
            return $this->output(1,'操作成功');
        }
        return $this->output(0,'操作失败');
    }

    public function createRootNode(Request $request){
        $nestedList = Chapters::getNestedList('title','id','+');
        dd($nestedList);

        dd(Chapters::roots()->first()->getDescendantsAndSelf()->toArray());
        $nestedList = Chapters::roots()->get()->toArray();

        dd($nestedList);
        $root = Chapters::create(['title'=>'测试']);
        $child2 = Chapters::create(['name' => 'Child 2']);
        $child2->makeChildOf($root);

    }


}